package Controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jackc/pgtype"
	"m/Global"
	"m/Model"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func EmployeeAdd(context *gin.Context) {
	var requestEmployee Model.Employee
	json.NewDecoder(context.Request.Body).Decode(&requestEmployee)
	fmt.Println("即将新增的员工：", requestEmployee)
	var err error
	//查询员工是否重复
	err = Global.Db.Table("employees").Where("id = ?", requestEmployee.Id).Error
	if err != nil {
		fmt.Println("员工重复！")
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "该员工已存在",
		})
		return
	}
	//根据现有员工数量生成员工编号
	var temEmployee Model.Employee
	Global.Db.Last(&temEmployee)
	var count int
	id, err := strconv.Atoi(temEmployee.Id)
	count = id + 1
	fmt.Println("生成的员工编号：", count)
	Sid := strconv.Itoa(count)
	var newEmployee Model.Employee
	newEmployee.Id = Sid
	newEmployee.Password = requestEmployee.Password
	newEmployee.Employee_type = requestEmployee.Employee_type
	newEmployee.Name = requestEmployee.Name
	newEmployee.Sex = requestEmployee.Sex
	newEmployee.Birthday = requestEmployee.Birthday
	newEmployee.Id_card = requestEmployee.Id_card
	newEmployee.Political = requestEmployee.Political
	newEmployee.Nation = requestEmployee.Nation
	newEmployee.Native_place = requestEmployee.Native_place
	newEmployee.Phone = requestEmployee.Phone
	newEmployee.Email = requestEmployee.Email
	newEmployee.Height = requestEmployee.Height
	newEmployee.Blood_type = requestEmployee.Blood_type
	newEmployee.Marital_status = requestEmployee.Marital_status
	newEmployee.Birthplace = requestEmployee.Birthplace
	newEmployee.Registered_residence = requestEmployee.Registered_residence
	newEmployee.Department_number = requestEmployee.Department_number
	newEmployee.Department_name = requestEmployee.Department_name
	newEmployee.Post_number = requestEmployee.Post_number
	newEmployee.Post_name = requestEmployee.Post_name
	newEmployee.Entry_date = time.Unix(time.Now().Unix(), 0).Format("2006-01-02")
	newEmployee.Employment_form = requestEmployee.Employment_form
	newEmployee.Personnel_source = requestEmployee.Personnel_source
	newEmployee.Highest_education = requestEmployee.Highest_education
	newEmployee.Graduation_school = requestEmployee.Graduation_school
	newEmployee.Major_studied = requestEmployee.Major_studied
	newEmployee.Graduation_date = requestEmployee.Graduation_date
	newEmployee.Is_quit = requestEmployee.Is_quit
	newEmployee.Qualifying_result = requestEmployee.Qualifying_result
	newEmployee.Qualifying_remark = requestEmployee.Qualifying_remark
	newEmployee.Qualifying_date = requestEmployee.Qualifying_date
	newEmployee.Starting_time = requestEmployee.Starting_time
	newEmployee.Ending_time = requestEmployee.Ending_time
	newEmployee.Company_name = requestEmployee.Company_name
	newEmployee.Work_unit = requestEmployee.Work_unit
	newEmployee.Fill_post = requestEmployee.Fill_post
	newEmployee.Salary = requestEmployee.Salary
	newEmployee.References = requestEmployee.References
	newEmployee.References_position = requestEmployee.References_position
	newEmployee.References_telephone = requestEmployee.References_telephone
	newEmployee.Foreign_languages = requestEmployee.Foreign_languages
	newEmployee.Language_proficiency = requestEmployee.Language_proficiency
	newEmployee.Relationship_myself = requestEmployee.Relationship_myself
	newEmployee.Family_name = requestEmployee.Family_name
	newEmployee.Family_Companyname = requestEmployee.Family_Companyname
	newEmployee.Position = requestEmployee.Position
	newEmployee.Telephone = requestEmployee.Telephone
	/*查找重复的员工ID*/
	err = Global.Db.Where("id_card = ?", requestEmployee.Id_card).First(&requestEmployee).Error
	if err == nil {
		fmt.Println("找到重复的身份证号")
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "该员工已存在",
		})
		return
	}
	/*查找部门编号是否存在*/
	err = Global.Db.Where("department_number = ?", requestEmployee.Department_number).First(&Model.Department{}).Error
	if err != nil {
		fmt.Println("找不到此部门编号")
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "部门编号不存在",
		})
		return
	}
	/*查找岗位编号是否存在*/
	err = Global.Db.Where("post_number = ?", requestEmployee.Post_number).First(&Model.PostTable{}).Error
	if err != nil {
		fmt.Println("找不到此岗位编号")
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "岗位编号不存在",
		})
		return
	}
	/*检查部门编号和部门名称是否对应*/
	var tempDepartment Model.Department
	Global.Db.Where("department_name = ?", requestEmployee.Department_name).First(&tempDepartment) //根据请求来的部门名称检查是否与部门编号所对应
	if requestEmployee.Department_number != tempDepartment.Department_number {
		fmt.Println("部门编号与名称不对应")
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "部门编号与名称不对应",
		})
		return
	}
	/*检查岗位编号和名称是否对应*/
	var tempPost Model.PostTable
	Global.Db.Where("post_name = ?", requestEmployee.Post_name).First(&tempPost)
	if requestEmployee.Post_number != tempPost.Post_number {
		fmt.Println("岗位编号与名称不对应")
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "岗位编号与名称不对应",
		})
		return
	}
	fmt.Println("即将新增员工：", newEmployee)
	err = Global.Db.Create(&newEmployee).Error
	if err != nil {
		fmt.Println("新增员工出错", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "新增员工出错",
		})
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "新增成功",
	})

}

func PersonReports(context *gin.Context) {

	var requestReport Model.PersonReport
	var request Model.PersonReport
	var reportP []Model.PersonReport
	//var requestTransferEmployee Model.DepartmentTransferEmployeeTable
	var requestDepartment Model.Department
	var err error
	err = Global.Db.Find(&requestDepartment).Error
	if err != nil {
		fmt.Println("查询部门表错误：", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询部门表出错",
		})
		return
	}
	err = Global.Db.Find(&reportP).Error
	if err != nil {
		fmt.Println("查询部门表错误：", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询部门表出错",
		})
		return
	}

	fmt.Println("表：：", reportP)
	var requestEmployee []Model.Employee
	err = Global.Db.Find(&requestEmployee).Error
	if err != nil {
		fmt.Println("查询部门表错误：", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询部门表出错",
		})
		return
	}

	requestDate := make(map[string]interface{})
	context.ShouldBind(&requestDate)
	fmt.Println(requestDate)
	startDate := requestDate["start"].(string)
	endDate := requestDate["end"].(string)
	fmt.Println("开始日期：", startDate)
	fmt.Println("结束日期：", endDate)
	start := strings.Split(startDate, "-")
	end := strings.Split(endDate, "-")
	fmt.Println("@", start[0], "@", start[1], "@", start[4])
	fmt.Println("@", end[0], "@", end[1], "@", end[4])
	tempStart, _ := time.Parse("2006-01-02", start[0]+"-"+start[1]+"-"+start[4])
	tempEnd, _ := time.Parse("2006-01-02", end[0]+"-"+end[1]+"-"+end[4])
	fmt.Println(tempStart, tempEnd)
	start1 := pgtype.Date{tempStart, 2, 0}
	end1 := pgtype.Date{tempEnd, 2, 0}
	var employee []Model.Employee
	err = Global.Db.Where("entry_date <= ?", start[0]+"-"+start[1]+"-"+"99").Find(&employee).Error
	if err != nil {
		fmt.Println("查找指定日期区间的员工出错", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查找指定日期区间的员工出错",
		})
		return
	}

	fmt.Println(len(employee))
	Date := strings.Split(startDate, "-")
	fmt.Println("分割后年月日为", Date)
	fmt.Println("查找结果：", employee)

	request.Month, _ = strconv.Atoi(Date[1])
	err = Global.Db.Table("person_reports").Where("month =?", request.Month).Delete(&request).Error
	if err != nil {
		fmt.Println("人事月报插入数据失败：", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "人事月报插入数据失败",
		})
		return
	}
	//requestReport.High_school = 0
	//requestReport.Junior_school = 0
	//requestReport.Undergraduate_school = 0
	//requestReport.Graduate_school = 0

	for i := 0; i < len(employee); i++ {
		var tempCount int64
		var temp1 int64
		var temp2 int64
		var count1 int64
		var count2 int64
		var count3 int64
		var count4 int64
		var count int64
		var count5 int
		var temp3 int
		var temp4 int

		err = Global.Db.Table("departments").Where("department_name = ?", employee[i].Department_name).First(&requestDepartment).Error
		err = Global.Db.Table("employees").Where("department_name =? and entry_date <= ?", requestDepartment.Department_name, start[0]+"-"+start[1]+"-"+"99").Count(&tempCount).Error
		s := Date[1]
		a, _ := strconv.Atoi(s)
		err = Global.Db.Table("person_reports").Where("month =? and department_name =?", a-1, requestDepartment.Department_name).Count(&count).Error
		if err != nil {
			fmt.Println("上月份不存在")
		} else {
			countx := strconv.FormatInt(count, 10)
			count5, _ = strconv.Atoi(countx)
			requestReport.Number_begin = count5
			fmt.Println("月初人数：", requestReport.Number_begin) //10
		}
		strint64 := strconv.FormatInt(tempCount, 10)
		requestReport.Number_end, _ = strconv.Atoi(strint64)
		fmt.Println("月末人数tempCount：", tempCount)
		fmt.Println("月末人数：", requestReport.Number_end) //3
		//err = Global.Db.Table("department_transfer_employee_tables").Where("department_name = ?", requestDepartment.Department_name).Count(&tempCount).Error
		err = Global.Db.Table("department_transfer_employee_tables").Where("transfer_date >=? and transfer_date <= ? and new_department_name =?", start1, end1, employee[i].Department_name).Count(&temp1).Error
		if err == nil {
			tempx := strconv.FormatInt(temp1, 10)
			temp3, _ = strconv.Atoi(tempx)
			requestReport.Move_in = temp3 //8
			fmt.Println("调入人数：", requestReport.Move_in)
		}

		err = Global.Db.Table("department_transfer_employee_tables").Where("transfer_date >=? and transfer_date <= ? and original_department_name =?", start1, end1, employee[i].Department_name).Count(&temp2).Error
		if err == nil {
			tempy := strconv.FormatInt(temp2, 10)
			temp4, _ = strconv.Atoi(tempy)
			requestReport.Move_out = temp4 //9
			fmt.Println("调出人数：", requestReport.Move_out)

		}

		requestReport.Department_name = requestDepartment.Department_name
		fmt.Println("部门名称：", requestReport.Department_name) //1

		fmt.Println("插入月份", s)
		requestReport.Month, _ = strconv.Atoi(s)
		fmt.Println("月份：", requestReport.Month) //2

		//
		err = Global.Db.Table("person_reports").Where("department_name=? and month =?", employee[i].Department_name, requestReport.Month).Find(&reportP).Error
		if err != nil { //部门不存在与人月表，将值制0
			count1 = 0
			count2 = 0
			count3 = 0
			count4 = 0
			fmt.Println("部门存在")
		}
		//count1 = reportP[i].High_school
		//count2 = reportP[i].Junior_school
		//count3 = reportP[i].Undergraduate_school
		//count4 = reportP[i].Graduate_school
		err = Global.Db.Table("employees").Where("department_name =? and entry_date <= ? and highest_education =? or highest_education =? or highest_education =? or highest_education =?", requestDepartment.Department_name, start[0]+"-"+start[1]+"-"+"99", "小学", "初中", "中专或高中", "其他").Count(&count1).Error
		err = Global.Db.Table("employees").Where("department_name =? and entry_date <= ? and highest_education =?", requestDepartment.Department_name, start[0]+"-"+start[1]+"-"+"99", "专科").Count(&count2).Error
		err = Global.Db.Table("employees").Where("department_name =? and entry_date <= ? and highest_education =?", requestDepartment.Department_name, start[0]+"-"+start[1]+"-"+"99", "本科").Count(&count3).Error
		err = Global.Db.Table("employees").Where("department_name =? and entry_date <= ? and highest_education =? or highest_education =?", requestDepartment.Department_name, start[0]+"-"+start[1]+"-"+"99", "硕士", "博士").Count(&count4).Error

		count11 := strconv.FormatInt(count1, 10)
		requestReport.High_school, _ = strconv.Atoi(count11)
		count12 := strconv.FormatInt(count2, 10)
		requestReport.Junior_school, _ = strconv.Atoi(count12)
		count13 := strconv.FormatInt(count3, 10)
		requestReport.Undergraduate_school, _ = strconv.Atoi(count13)
		count14 := strconv.FormatInt(count4, 10)
		requestReport.Graduate_school, _ = strconv.Atoi(count14)
		err = Global.Db.Table("person_reports").Where("department_name = ? and month =?", employee[i].Department_name, requestReport.Month).Delete(&requestReport).Error
		if err == nil {
			fmt.Println("找到重复的月份,即将更新")
		}
		err = Global.Db.Table("person_reports").Create(&requestReport).Error
		if err != nil {
			fmt.Println("人事月报插入数据失败：", err)
			context.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "人事月报插入数据失败",
			})
			return
		}
		fmt.Println("更新后的人月报表：", requestReport)
		context.JSON(http.StatusOK, gin.H{
			"data": requestReport,
			"msg":  "人月表计算成功",
		})

	}

}

func PersonBasic(context *gin.Context) {
	var Person []Model.PersonReport
	var err error
	err = Global.Db.Find(&Person).Error
	if err != nil {
		fmt.Println("查询人事表出错", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询人事表出错",
		})
		return
	}
	fmt.Println("所有人事表信息：", Person)
	context.JSON(http.StatusOK, Person)
}
func Searchreport(context *gin.Context) {
	var requestReport Model.PersonReport
	json.NewDecoder(context.Request.Body).Decode(&requestReport)
	fmt.Println("前端传入的数据为", requestReport)
	fmt.Println("查询月份为：", requestReport.Month)
	var person []Model.PersonReport
	err := Global.Db.Where("month = ?", requestReport.Month).Find(&person).Error
	if err != nil {
		fmt.Println("错误：", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询人月报表出错",
		})
		return
	}
	fmt.Println("查询到的人月报表：", person)
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": person,
		"msg":  "查询成功",
	})
}

func ApplyPostInformation(context *gin.Context) {
	var requestEmployee Model.Employee
	json.NewDecoder(context.Request.Body).Decode(&requestEmployee)
	fmt.Println("申请调动的员工信息：", requestEmployee)
	var employee []Model.Employee
	err := Global.Db.Where("id = ?", requestEmployee.Id).First(&employee).Error
	if err != nil {
		fmt.Println("错误：", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询员工出错",
		})
		return
	}
	fmt.Println("查询到的员工：", employee)
	context.JSON(http.StatusOK, employee)
}

func ApplyNewPost(context *gin.Context) {
	var requestApplication Model.PostApplications
	json.NewDecoder(context.Request.Body).Decode(&requestApplication)
	fmt.Println("请求的调动信息：", requestApplication)

	var err error
	var tempEmployee Model.Employee
	err = Global.Db.Where("id = ?", requestApplication.Id).First(&tempEmployee).Error
	if err != nil {
		fmt.Println("出错了", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查找员工出错",
		})
		return
	}
	requestApplication.Name = tempEmployee.Name
	requestApplication.Original_department_name = tempEmployee.Department_name
	requestApplication.Original_post_name = tempEmployee.Post_name

	var tempCount int64
	err = Global.Db.Table("post_applications").Count(&tempCount).Error
	if err != nil {
		fmt.Println("计算记录数量出错！", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "计算记录数量出错",
		})
		return
	}
	fmt.Println("记录数量：", tempCount)
	strInt64 := strconv.FormatInt(tempCount, 10)
	count, _ := strconv.Atoi(strInt64)
	requestApplication.Application_id = count

	fmt.Println("即将写入的申请信息：", requestApplication)

	var tempApplication Model.PostApplications
	err = Global.Db.Where("id = ? and original_department_name = ? and new_department_name = ? and original_post_name = ? and new_post_name = ? and is_agree = ?", requestApplication.Id, requestApplication.Original_department_name, requestApplication.New_department_name, requestApplication.Original_post_name, requestApplication.New_post_name, 0).First(&tempApplication).Error
	if err == nil {
		fmt.Println("请勿重复提交！", tempApplication)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "请勿重复提交",
		})
		return
	}

	err = Global.Db.Create(&requestApplication).Error
	if err != nil {
		fmt.Println("写入申请信息出错！", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "写入申请信息出错",
		})
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "申请成功",
	})

}

func ApplyResignedInformation(context *gin.Context) {
	var requestEmployee Model.Employee
	json.NewDecoder(context.Request.Body).Decode(&requestEmployee)
	fmt.Println("申请离职的员工信息：", requestEmployee)
	var employee []Model.Employee
	err := Global.Db.Where("id = ?", requestEmployee.Id).First(&employee).Error
	if err != nil {
		fmt.Println("错误：", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询员工出错",
		})
		return
	}
	fmt.Println("查询到的员工：", employee)
	context.JSON(http.StatusOK, employee)
}

func ApplyResigned(context *gin.Context) {
	var requestResigned Model.ResignedEmployee
	json.NewDecoder(context.Request.Body).Decode(&requestResigned)
	fmt.Println("收到的离职申请：", requestResigned)

	var err error
	err = Global.Db.Table("employees").Where("id = ?", requestResigned.Id).Update("is_quit", "是").Error
	if err != nil {
		fmt.Println("更新员工信息表出错", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "更新员工信息表出错",
		})
		return
	}
	requestResigned.Resignation_date = time.Unix(time.Now().Unix(), 0).Format("2006-01-02 15:04:05")
	err = Global.Db.Create(&requestResigned).Error
	if err != nil {
		fmt.Println("写入离职信息表出错", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "写入离职信息表出错",
		})
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "离职成功",
	})
}

func EmployeeBasicByEmployee(context *gin.Context) {
	request := make(map[string]interface{})
	context.ShouldBind(&request)
	requestId := request["id"].(string)
	fmt.Println("登录的员工ID：", requestId)

	//根据员工id查找部门，返回此部门的所有同事
	var employees []Model.Employee
	var err error
	var employee Model.Employee
	err = Global.Db.Where("id = ?", requestId).First(&employee).Error
	if err != nil {
		fmt.Println("查找员工ID出错", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查找员工ID出错",
		})
		return
	}
	err = Global.Db.Where("department_name = ? and employee_type != ?", employee.Department_name, "总裁").Find(&employees).Error
	if err != nil {
		fmt.Println("查找员工部门的同事出错", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查找员工部门的同事出错",
		})
		return
	}
	context.JSON(http.StatusOK, employees)
}

func EmployeeBasicSearchByEmployee(context *gin.Context) {
	request := make(map[string]interface{})
	context.ShouldBind(&request)
	requestId := request["id"].(string)     //登录员工的id
	requestName := request["name"].(string) //要查找的姓名
	fmt.Println("id = ", requestId, ";name = ", requestName)
	var tempDepartment Model.Employee
	var err error
	err = Global.Db.Where("id = ?", requestId).First(&tempDepartment).Error
	if err != nil {
		fmt.Println("查找员工信息出错", err)
	}
	fmt.Println("员工信息：", tempDepartment)
	var employee []Model.Employee
	err = Global.Db.Where("name = ? and department_name = ? and employee_type != ?", requestName, tempDepartment.Department_name, "总裁").First(&employee).Error
	if err != nil {
		fmt.Println("未找到此员工")
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "未找到此员工",
		})
		return
	}
	fmt.Println("查询结果：", employee)
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": employee,
	})
}

func EmployeeBasicSearchDateByEmployee(context *gin.Context) {
	requestDate := make(map[string]interface{})
	context.ShouldBind(&requestDate)
	fmt.Println(requestDate)
	requestId := requestDate["id"].(string)
	startDate := requestDate["start"].(string)
	endDate := requestDate["end"].(string)
	fmt.Println("开始日期：", startDate)
	fmt.Println("结束日期：", endDate)
	tempStart, _ := time.Parse("2006-01-02", startDate)
	tempEnd, _ := time.Parse("2006-01-02", endDate)
	fmt.Println(tempStart, tempEnd)
	start := pgtype.Date{tempStart, 2, 0}
	end := pgtype.Date{tempEnd, 2, 0}
	fmt.Println("开始日期2：", start)
	fmt.Println("结束日期2：", end)
	var err error
	var temp Model.Employee
	err = Global.Db.Where("id = ?", requestId).First(&temp).Error
	var employee []Model.Employee
	err = Global.Db.Where("entry_date >= ? and entry_date <= ? and department_name = ? and employee_type != ?", start, end, temp.Department_name, "总裁").Find(&employee).Error
	if err != nil {
		fmt.Println("查找指定日期区间的员工出错", err)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查找指定日期区间的员工出错",
		})
		return
	}
	fmt.Println("查找结果：", employee)
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查找成功",
		"data": employee,
	})
}
